package tools_util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class ImageFileCache {
	private static final String CACHDIR = "imgCache";
	private static final String WHOLESALE_CONV = ".cach";

	private static final int MB = 1024 * 1024;
	private static final int CACHE_SIZE = 10;
	private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 10;

	public ImageFileCache() {
		// 清理文件缓存
		removeCache(getDirectory());
	}

	/** 从缓存中获取图片 **/
	public Bitmap getImage(final String url) {
		final String path = getDirectory() + "/" + convertUrlToFileName(url);
		File file = new File(path);
		if (file.exists()) {
			Bitmap bmp = BitmapFactory.decodeFile(path);
			if (bmp == null) {
				file.delete();
			} else {
				updateFileTime(path);
				return bmp;
			}
		}
		return null;
	}

	/**
	 * 将图片放入文件缓�?
	 * 
	 * @param bitmap
	 * @param url
	 */
	public void saveBitmap(Bitmap pBm, Bitmap bm, String url) {
		if (bm == null) {
			return;
		}
		// 判断SD卡上的空�?
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			// SD卡空间不�?
			return;
		}
		String fileName = convertUrlToFileName(url);
		String pFileName = convertUrlToPressFileName(url);
		String dir = getDirectory();
		File dirFile = new File(dir);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File file = new File(dir + "/" + fileName);
		try {
			file.createNewFile();
			OutputStream ot = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.PNG, 100, ot);// 100是压缩率，表示压�?;如果压缩�?，表示压缩率�?00
			ot.flush();
			ot.close();
			if (pBm != null) {
				File pFile = new File(dir + "/" + pFileName);
				OutputStream ot1 = new FileOutputStream(pFile);
				pBm.compress(Bitmap.CompressFormat.PNG, 100, ot1);
				ot1.flush();
				ot1.close();
			}
		} catch (FileNotFoundException e) {
			Log.w("ImageFileCache", "FileNotFoundException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w("ImageFileCache", "IOException");
		}

	}

	/**
	 * 处理压缩图片的名�?
	 * 
	 * @param url
	 * @return
	 */
	public String convertUrlToPressFileName(String url) {
		// TODO Auto-generated method stub
		String[] strs = url.split("/");
		String str = strs[strs.length - 1];
		return "p_" + str;

	}

	/**
	 * 计算存储目录下的文件大小�?
	 * 当文件�?大小大于规定的CACHE_SIZE或�?sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规�?
	 * 那么删除40%�?��没有被使用的文件
	 */
	private boolean removeCache(String dirPath) {
		// TODO Auto-generated method stub
		File dir = new File(dirPath);
		File[] files = dir.listFiles();
		if (files == null) {
			return true;
		}
		if (!Environment.getExternalStorageDirectory().equals(
				Environment.MEDIA_MOUNTED)) {
			return false;
		}
		int dirSize = 0;
		for (int i = 0; i < files.length; i++) {
			if (files[i].getName().contains(WHOLESALE_CONV)) {
				dirSize += files[i].length();
			}
		}
		if (dirSize > CACHE_SIZE * MB
				|| FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			int removeFactor = (int) ((0.4 * files.length) + 1);
			Arrays.sort(files, new FileLastModifSort());
			for (int i = 0; i < removeFactor; i++) {
				if (files[i].getName().contains(WHOLESALE_CONV)) {
					files[i].delete();
				}
			}
		}
		if (freeSpaceOnSd() <= CACHE_SIZE) {
			return false;
		}
		return true;
	}

	/** 修改文件的最后修改时�? **/
	public void updateFileTime(String path) {
		File file = new File(path);
		long newModifiedTime = System.currentTimeMillis();
		file.setLastModified(newModifiedTime);
	}

	/** 将url转换成文件名 */
	public String convertUrlToFileName(String url) {
		// TODO Auto-generated method stub
		String[] strs = url.split("/");
		return strs[strs.length - 1];
	}

	/**
	 * 计算SD卡剩余空�?
	 * 
	 * @return
	 */
	private int freeSpaceOnSd() {
		// TODO Auto-generated method stub
		StatFs sf = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) sf.getAvailableBlocks() * (double) sf
				.getBlockSize()) / MB;
		return (int) sdFreeMB;
	}

	/**
	 * 获得缓存目录
	 * 
	 * @return
	 */
	private String getDirectory() {
		// TODO Auto-generated method stub
		String path = getSDPath() + "/" + CACHDIR;
		return path;
	}

	/**
	 * 获得SD卡路�?
	 * 
	 * @return
	 */
	private String getSDPath() {
		// TODO Auto-generated method stub
		File sdPath = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);// 判断SD卡是否存�?
		if (sdCardExist) {
			sdPath = Environment.getExternalStorageDirectory();// 获取根目�?
		}
		if (sdPath != null) {
			return sdPath.toString();
		} else {

			return "";
		}
	}

	/**
	 * 根据文件�?��修改的时间排�?
	 * 
	 * @author Administrator
	 * 
	 */
	private class FileLastModifSort implements Comparator<File> {

		@Override
		public int compare(File lhs, File rhs) {
			// TODO Auto-generated method stub
			if (lhs.lastModified() > rhs.lastModified()) {
				return 1;
			} else if (lhs.lastModified() == rhs.lastModified()) {
				return 0;
			} else {
				return -1;
			}
		}

	}
}
